package com.evl.ticketRemainder.service.impl;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.plugins.Page;
import com.evl.api.ticket.service.ITicketService;
import com.evl.common.constant.Const;
import com.evl.common.persistence.dao.ScheduleStationMapper;
import com.evl.common.persistence.dao.StationSeatRMapper;
import com.evl.common.persistence.dao.TicketRemainderMapper;
import com.evl.common.persistence.dao.TrainSeatScheduleMapper;
import com.evl.common.persistence.model.ScheduleStation;
import com.evl.common.persistence.model.StationSeatR;
import com.evl.common.persistence.model.TicketRemainder;
import com.evl.common.persistence.model.TrainSeatSchedule;
import com.evl.constant.TrainSeatStatus;
import com.evl.constant.TrainSeatType;
import com.evl.ticketRemainder.service.ITicketRemainderService;
import com.evl.ticketRemainder.vo.TrainSeatScheduleVo;
import com.evl.trainSeat.service.ITrainSeatService;
import com.evl.utils.DateUtils;

/**
 * <p>
 * 余票表 服务实现类
 * </p>
 *
 * @author yangliwei
 * @since 2017-06-21
 */
@Service
@Transactional
public class TicketRemainderServiceImpl  implements ITicketRemainderService {
	
	private Logger log = Logger.getLogger(this.getClass());

	@Resource
	TicketRemainderMapper ticketRemainderMapper;
	
	@Resource
	ScheduleStationMapper scheduleStationMapper;
	
	@Resource
	ITrainSeatService trainSeatService;
	
	@Resource
	TrainSeatScheduleMapper trainSeatScheduleMapper;
	
	@Resource
	StationSeatRMapper stationSeatRMapper;
	
	@Resource
	ITicketService ticketService;
	
	@Override
	public List<TicketRemainder> selectTicketRemaindersPage(Page<TicketRemainder> page, String departure, String arrive,String date) {
		
		List<TicketRemainder> list = new ArrayList<TicketRemainder>();
		if(StringUtils.isNotEmpty(date)){
			Date []dateArr = new Date[]{};
			try {
				dateArr =DateUtils.getcurrDayArr(date);
			} catch (ParseException e) {
				log.error("date transform error");
			}
		
			String startTime = DateUtils.getSpecifyDate(dateArr[0], DateUtils.FORMAT_YYYY_MM_DD_HH_MI_SS);
			String endTime = DateUtils.getSpecifyDate(dateArr[1], DateUtils.FORMAT_YYYY_MM_DD_HH_MI_SS);
		
			list = ticketRemainderMapper.selectTicketRemaindersPage(page, departure, arrive ,startTime ,endTime);
		}
		return list;
	}

	@Override
	public List<TicketRemainder> selectTicketRemainders(String departure,
			String arrive, String date) {
		List<TicketRemainder> list = new ArrayList<TicketRemainder>();
		if(StringUtils.isNotEmpty(date)){
			Date []dateArr = new Date[]{};
			try {
				dateArr =DateUtils.getcurrDayArr(date);
			} catch (ParseException e) {
				log.error("date transform error");
			}
		
			String startTime = DateUtils.getSpecifyDate(dateArr[0], DateUtils.FORMAT_YYYY_MM_DD_HH_MI_SS);
			String endTime = DateUtils.getSpecifyDate(dateArr[1], DateUtils.FORMAT_YYYY_MM_DD_HH_MI_SS);
		
			list = ticketRemainderMapper.selectTicketRemainders(departure, arrive ,startTime ,endTime);
		}
		return list;
	}

	@Override
	public TicketRemainder selectTicketOne(int staId, String departure,	String arrive) {
		return ticketRemainderMapper.selectTicketOne(staId,departure,arrive);
	}

	@Override
	public TicketRemainder selectTicketById(Integer ticketRemainderId) {
		return this.ticketRemainderMapper.selectById(ticketRemainderId);
	}

	@Override
	public List<TrainSeatScheduleVo> getTrainSeatSchedules(TicketRemainder tr, String carriageNo, String seatNo, String seatType) {
		
		//获取出发站至到达站的的站点线路信息
		List<ScheduleStation> scheduleStationList = trainSeatService.getStationLine(String.valueOf(tr.getStaId()), tr.getDeparture(), tr.getArrive());
			
		//查询车次所有的座位
		List<TrainSeatSchedule> seatScheduleList = trainSeatScheduleMapper.selectTrainSeatSchedules(tr.getStaId(),carriageNo,seatNo,seatType);
		
		//TODO 获取对应站点的座位列表（可选）存入map集合 --可以抽取公共方法
		Map<Integer,List<Integer>> map = new HashMap<Integer, List<Integer>>();
		for (ScheduleStation ss : scheduleStationList){
			//TODO 一次性查询，在后台解析
			List<Integer> seatIdList = stationSeatRMapper.selectStationSeatIds(ss.getId());
			map.put(ss.getId(), seatIdList);
		}
		
		//获取每个站点的座位id列表（可选）的交集
		List<Integer> intersectionList = new ArrayList<Integer>();
		for(Map.Entry<Integer, List<Integer>> entry : map.entrySet()){
			if(intersectionList.size() == 0){//如何集合为空，赋值
				intersectionList = entry.getValue();
			} else{//取各个站点的集合交集
				intersectionList.retainAll(entry.getValue());
			}
		}
			
		List<TrainSeatScheduleVo> list = new ArrayList<TrainSeatScheduleVo>();
		for(TrainSeatSchedule tss : seatScheduleList){
			TrainSeatScheduleVo tssVo= new TrainSeatScheduleVo(null, null, null);
				
			tssVo.setId(tss.getId());
			tssVo.setStaId(tss.getStaId());
			tssVo.setCarriageNo(tss.getCarriageNo());
			tssVo.setSeatNo(tss.getSeatNo());
			tssVo.setSeatType(tss.getSeatType());
			tssVo.setSeatTypeName(TrainSeatType.valueOf(Integer.parseInt(tssVo.getSeatType())));
			tssVo.setSeatStatus(intersectionList.contains(tss.getId()) == true ? Const.SEAT_CHOOSABLE : Const.SEAT_LOCKED);
			tssVo.setSeatStatusName(TrainSeatStatus.valueOf(tssVo.getSeatStatus()));
			if(tssVo.getSeatStatus() == Const.SEAT_LOCKED){
				StationSeatR stationSeatR = stationSeatRMapper.selectStationSeatROne(tssVo);
				if(stationSeatR != null){
					tssVo.setIdentification(stationSeatR.getIdentification());
				}
			}
			list.add(tssVo);
				
		}

		return list;
	}

	@Override
	public void lockSeats(Integer ticketRemainderId,String[] trainSeatScheduleIds) {
		
		TicketRemainder tr = selectTicketById(ticketRemainderId);
    	
    	//获取出发站至到达站的的站点线路信息
		List<ScheduleStation> sStaionList = trainSeatService.getStationLine(String.valueOf(tr.getStaId()), tr.getDeparture(), tr.getArrive());
		
		List<StationSeatR> stationSeatRList = new ArrayList<StationSeatR>();
		//封装站点与座位的关系
		for(ScheduleStation scheduleStation : sStaionList){
			
			for(String trainSeatId : trainSeatScheduleIds){
				
				StationSeatR stationSeatR = new StationSeatR();
				stationSeatR.setStationId(scheduleStation.getId());
				stationSeatR.setSeatId(Integer.parseInt(trainSeatId));
				stationSeatR.setSeatStatus(Const.SEAT_LOCKED);
				stationSeatR.setIdentification("LOCKED");
				
				stationSeatRList.add(stationSeatR);
			}
			
		}
		
		if(stationSeatRList !=null && stationSeatRList.size()>0){
			stationSeatRMapper.batchUpdate(stationSeatRList);
		}
		
	}
	
	@Override
	public void canclelockSeats(Integer ticketRemainderId,String[] trainSeatScheduleIds) {
		
		TicketRemainder tr = selectTicketById(ticketRemainderId);
    	
    	//获取出发站至到达站的的站点线路信息
		List<ScheduleStation> sStaionList = trainSeatService.getStationLine(String.valueOf(tr.getStaId()), tr.getDeparture(), tr.getArrive());
		
		List<StationSeatR> stationSeatRList = new ArrayList<StationSeatR>();
		//封装站点与座位的关系
		for(ScheduleStation scheduleStation : sStaionList){
			
			for(String trainSeatId : trainSeatScheduleIds){
				
				StationSeatR stationSeatR = new StationSeatR();
				stationSeatR.setStationId(scheduleStation.getId());
				stationSeatR.setSeatId(Integer.parseInt(trainSeatId));
				
				StationSeatR ssrVo = stationSeatRMapper.selectByStationIdSeatId(stationSeatR);
				if(ssrVo == null){
					continue;
				}
				stationSeatR.setSeatStatus(Const.SEAT_CHOOSABLE);
				stationSeatR.setIdentification(null);
				
				stationSeatRList.add(stationSeatR);
			}
			
		}
		
		if(stationSeatRList !=null && stationSeatRList.size()>0){
			stationSeatRMapper.batchCancleLock(stationSeatRList);
		}
		
	}

	@Override
	public List<ScheduleStation> getScheduleStations(TicketRemainder tr) {
		//获取出发站至到达站的的站点线路信息
		List<ScheduleStation> sStaionList = ticketService.selectScheduleStations(tr.getStaId());
		
		return sStaionList;
	}
	
}
